#include "libc.h" 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>


MyFile* BuyFile(int fd,int flag)
{
    MyFile * file = (MyFile*) malloc(sizeof(MyFile));
    if(file == NULL) return NULL;
    file->bufferlen = 0;
    file->fileno = fd;
    file->flag = flag;
    file->flush_method = LINE_FLUSH;
    memset(file->outbuffer,0,sizeof(file->outbuffer));
    return file;
}

MyFile * MyOpen(const char* path,const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode,"w") == 0)
    {
        flag = O_CREAT |  O_WRONLY| O_TRUNC;
        fd = open(path,flag,0666);    
    }
    else if(strcmp(mode,"r") == 0)
    {
        flag = O_RDWR;
        fd = open(path,flag);    
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag = O_CREAT |  O_WRONLY| O_APPEND;
        fd = open(path,flag,0666);    
    }
    else
    {}
    if(fd < 0) return NULL;
    MyFile* myFile = BuyFile(fd,flag);
    return myFile;
}
void MyClose(MyFile* file)
{
    if(file ==NULL||file->fileno < 0) return;
    MyFFlush(file);
    close(file->fileno);
    free(file);    
    return;
}


int MyFwrite(MyFile * file,void* str,int len)
{
    memcpy(file->outbuffer+file->bufferlen,str,len);
    file->bufferlen+=len;
    if((file->flush_method&LINE_FLUSH)&&file->outbuffer[file->bufferlen -1] == '\n')
        {
            MyFFlush(file);
        }
    return 0;
}
void MyFFlush(MyFile * file)
{   
   if(file->bufferlen == 0) return;  
    write(file->fileno,file->outbuffer,file->bufferlen);
    file->bufferlen = 0;
}
